# 1. 导包
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

# 2. 初始化浏览器驱动
service = Service(r"D:/chrome_driver/chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get('https://hmshop-test.itheima.net/Home/user/login.html')
action = ActionChains(driver)
driver.maximize_window()
driver.implicitly_wait(30)

try:
    # 3. 访问目标网站
    driver.set_page_load_timeout(30)
    try:
        driver.get('https://hmshop-test.itheima.net/')
    except:
        driver.execute_script('window.stop()')
    time.sleep(3)

    # 4. 点击登录按钮
    login_link = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.CLASS_NAME, 'red'))
    )
    login_link.click()
    time.sleep(3)

    # 5. 填写登录信息
    driver.find_element(By.ID, 'username').send_keys('15344591092')
    time.sleep(2)
    driver.find_element(By.ID, 'password').send_keys('lyw583580')
    time.sleep(2)
    driver.find_element(By.ID, 'verify_code').send_keys('8888')
    time.sleep(2)

    # 6. 提交登录
    login_button = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.CLASS_NAME, 'J-login-submit'))
    )
    login_button.click()
    time.sleep(5)

    # 7. 搜索"华为"
    search_input = driver.find_element(By.ID, 'q')
    search_input.send_keys('华为')
    time.sleep(2)
    driver.find_element(By.CLASS_NAME, 'search_usercenter_btn').click()
    time.sleep(5)

    # 8. 搜索结果页点击"加入购物车"
    add_cart_btn1 = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, '//a[contains(@onclick, "AjaxAddCart(13")]'))
    )
    add_cart_btn1.click()
    time.sleep(4)

    # 9. 详情页点击"加入购物车"
    try:
        join_cart_btn = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.ID, 'join_cart'))
        )
        join_cart_btn.click()
    except:
        print("详情页加入购物车按钮未找到，刷新页面重试")
        driver.refresh()
        join_cart_btn = WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.ID, 'join_cart'))
        )
        join_cart_btn.click()
    time.sleep(5)  # 延长弹窗加载等待时间


    # 10. 处理加入购物车弹窗（核心优化部分）
    try:
        # 先等待弹窗外层容器出现（确保弹窗已加载）
        print("等待弹窗外层容器加载...")
        popup_container = WebDriverWait(driver, 30).until(  # 延长至30秒等待弹窗出现
            EC.presence_of_element_located((By.CLASS_NAME, 'layui-layer-iframe'))  # 弹窗外层通用类
        )
        print("弹窗外层容器已加载")

        # 定位iframe（优先用id，若失败则用name或xpath）
        try:
            # 尝试通过id定位（兼容动态id，如layui-layer-iframe1/2）
            cart_iframe = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH, '//iframe[contains(@id, "layui-layer-iframe")]'))
            )
        except:
            # 备用：通过name定位
            cart_iframe = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH, '//iframe[contains(@name, "layui-layer-iframe")]'))
            )
        driver.switch_to.frame(cart_iframe)
        print("已切换到弹窗iframe")

    except TimeoutException:
        print("弹窗加载超时，尝试刷新页面后重试")
        driver.refresh()
        time.sleep(3)
        # 刷新后重新处理弹窗
        popup_container = WebDriverWait(driver, 30).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'layui-layer-iframe'))
        )
        cart_iframe = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.XPATH, '//iframe[contains(@id, "layui-layer-iframe")]'))
        )
        driver.switch_to.frame(cart_iframe)


    # 11. 弹窗内点击"去购物车结算"（根据用户提供的按钮代码定位）
    go_cart_btn = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, '//a[contains(@href, "/index.php/Home/Cart/index.html") and text()="去购物车结算"]'))
    )
    go_cart_btn.click()
    print("已点击去购物车结算")
    time.sleep(5)

    # 切回主页面
    driver.switch_to.default_content()

    # 12. 购物车页面点击"去结算"
    checkout_btn = WebDriverWait(driver, 25).until(
        EC.element_to_be_clickable((By.XPATH, '//a[contains(@class, "paytotal") and contains(@data-url, "/index.php/Home/Cart/cart2.html")]'))
    )
    checkout_btn.click()
    time.sleep(5)

    # 13. 结算页面点击"提交订单"
    try:
        submit_order_btn = WebDriverWait(driver, 25).until(
            EC.element_to_be_clickable((By.ID, 'submit_order'))
        )
        submit_order_btn.click()
    except:
        print("提交订单按钮未找到，尝试滚动页面")
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        submit_order_btn = WebDriverWait(driver, 25).until(
            EC.element_to_be_clickable((By.ID, 'submit_order'))
        )
        submit_order_btn.click()
    time.sleep(5)

    # 14. 点击“确认支付方式”按钮完成支付
    confirm_pay_btn = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, '//a[contains(@class, "button-confirm-payment") and text()="确认支付方式"]'))
    )
    confirm_pay_btn.click()
    print("已点击确认支付方式，完成支付流程")

    print("全流程执行完成，当前为支付确认后页面")
    input("按回车键关闭浏览器...")

finally:
    driver.quit()